package com.futonredemption.batterytest;

import org.beryl.app.ServiceForegrounder;

import android.app.IntentService;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

/**
 * Features needed:
 * - Wake Lock Management
 * - Foregrounding
 * - 
 *
 * Based on: https://github.com/commonsguy/cwac-wakeful/blob/master/src/com/commonsware/cwac/wakeful/WakefulIntentService.java
 */
public abstract class WorkerService extends IntentService {
	
	public WorkerService() {
		this("WorkerService");
	}
	
	public WorkerService(String name) {
		super(name);
		this.setIntentRedelivery(true);
	}

	ServiceForegrounder foregrounder = new ServiceForegrounder(this, 0);

	@Override
	public void onStart(Intent intent, int startId) {
	    handleCommand(intent);
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		
		if ((flags & START_FLAG_REDELIVERY) != 0) {
			getLock(this).acquire();
		}

		super.onStartCommand(intent, flags, startId);

	    return START_REDELIVER_INTENT;
	}

	@Override
	final protected void onHandleIntent(Intent intent) {
		try {
			handleCommand(intent);
		}
		finally {
			getLock(this).release();
		}
	}
	
	public abstract void handleCommand(Intent intent);
	
	public void startForeground(CharSequence title, CharSequence description, CharSequence tickerText) {
		final PendingIntent futureMainActivityIntent = getMainActivityIntent();
		foregrounder.startForeground(R.drawable.ic_stat_warning, title, description, tickerText, futureMainActivityIntent);
	}
	
	public void stopForeground() {
		foregrounder.stopForeground();
	}
	
	protected PendingIntent getMainActivityIntent() {
		final Intent intent = new Intent(this, BatteryTestActivity.class);
		final PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
		return pIntent;
	}
}
